/* $RCSFile: CRMImageBookItem.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ImageSettings/UI/WebControls/CRMImageBookItem.cs $
 * $log$
 * Revision 7 2010/08/09 09:44:02  christian.surieux
 *   Added Log to cs sources files
 */

using System;
using System.Xml;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

using AddonNice.Settings;
using AddonNice.Diagnostics;
using AddonNice.UI;
using AddonNice.Web.UI;
using AddonNice.UI.WebControls;
using AddonNice.Configuration;
using AddonNice.Core;
using AddonNice.Helpers;
using AddonNice.Settings.CRMImage;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.CRMImage.UI.WebControls
{
    /// <summary>
    /// CRMImageBookItem manages all the design extension for ImageBook
    /// It must contains a dataList which will receive individual images associated with each entity
    /// </summary>
    public class CRMImageBookItem : CRMImageItem
    {
		int imageItemID			=   1;// internal to count items on page
        int rowCount			=   0;// counter for rows to display when not under CRM, necessary for pager

        RepeatDirection _RepeatDirection = RepeatDirection.Horizontal;
        public RepeatDirection RepeatDirection    
        {
            get
            {
                return _RepeatDirection;
            }
            set
            {
                _RepeatDirection = value;
            }
        }

        int _RepeatColumns = 2;
	    public int RepeatColumns 
        {
            get
            {
                return _RepeatColumns;
            }
            set
            {
                _RepeatColumns = value;
            }
        }

	    public int RecordsPerPage 
        {
            get
            {
                return (int)ViewState["RecordsPerPage"];
            }
            set
            {
                ViewState["RecordsPerPage"] = value;
            }
        }


        string _ThumbnailLayout = string.Empty;
        public string ThumbnailLayout
        {
            get
            {
                return _ThumbnailLayout;
            }
            set
            {
                _ThumbnailLayout = value;
            }
        }

        /// <summary>
        /// EntityName read from DB when browsing records not under CRM
        /// </summary>
        public string DBEntityName
        {
            get
            {
                return GetMetadata(ImStr.MetaDBEntityName);
            }
        }
        
        /// <summary>
        /// value for the 'display name' attribute specified in the settings for ImageBook module
        /// </summary>
        public string AttachedName
        {
            get
            {
                return GetMetadata(ImStr.AttachedName);
            }
        }



        DataList _DLItems = null;
        public DataList DLItems
        {
            get
            {
                if ( _DLItems == null )
                    _DLItems = (DataList)FindControl("DLItems");
                return _DLItems;
            }
        }

        Paging _pgPictures = null;
        public Paging pgPictures
        {
            get
            {
                if ( _pgPictures == null )
                    _pgPictures = (Paging)FindControl("pgPictures");
                return _pgPictures;
            }
        }

        public override bool ImageIsEditable
        {
            get
            {
                return false;
            }
        }

        public override string StdArgString
        {
            get
            {
				string str  =   string.Format("ImageDBID={0}&ItemCrmID={1}&typename={2}&id={3}&mid={4}&DBEntityName={5}&PageNum={6}&ParentPageNum={7}",
                    new object[]{GetMetadata(ImStr.ImageDBID),
                        GetMetadata(ImStr.ItemCrmID),
                        GetMetadata(ImStr.RequestEntityName),
                        GetMetadata(ImStr.EntityID),
                        GetMetadata(ImStr.ModuleID),
                        DBEntityName,
                        GetMetadata(ImStr.PageNum),
                        GetMetadata(ImStr.ParentPageNum)});
                    if ( CrmImageTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookItem StdArgString GET: {0}", str),CrmImageTrace.Sw.Info);
                return str;
            }
        }

        public override string imageEdit
		{
			get
			{
				return HttpUrlBuilder.BuildUrl(Config.ModulesPath+"/CRMImageBook/CRMImageBookEdit.aspx",StdArgString);
			}
		}
		public override string imageView
		{
			get
			{
				return HttpUrlBuilder.BuildUrl(Config.ModulesPath+"/CRMImage/CRMImageView.aspx",StdArgString);
			}
		}

        /// <summary>
		/// Attempt to cache the layout module name
		/// </summary>
		private string _layoutThumbnailModule	=	string.Empty;
		string layoutThumbnailModule
		{
			get
			{
				if (string.IsNullOrEmpty(_layoutThumbnailModule))
				{
					_layoutThumbnailModule = Config.ModulesPath + "/CRMImageBook/Layout/Thumbnails/" + ThumbnailLayout;
					if ( ModuleTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImage layoutModule: {0}", _layoutThumbnailModule),ModuleTraceSwitch.Sw.Info);
				}
				return _layoutThumbnailModule;
			}
		}

        /// <summary>
        /// Here we have already received from CRMImageBook an XML Metadata value to get all data readen from the ImgaBook record
        /// We will use the ImageBook DB key to read all attached images and bind them to CRMImageBookImageItems
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CRMImageBookItem_Load(object sender, System.EventArgs e)
        {
            DataBind(); // necessary ?? to check

			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookItem CRMImageBookItem_Load IsPostBack: {0}, IsInAsyncPostBack: {1}, PageNumber: {2}.",
                    IsPostBack,((ADNPage)Page).IsInAsyncPostBack,(pgPictures == null) ? 0:pgPictures.PageNumber),CrmImageTrace.Sw.Info);
            if ( pgPictures != null )
            {
                pgPictures.RecordsPerPage   =   RecordsPerPage;
                string ob                   =   Request.QueryString[ImStr.PageNum];
                string ob1                  =   Request.QueryString[ImStr.ItemCrmID];
                if (!string.IsNullOrEmpty(ob) && !string.IsNullOrEmpty(ob1))
                {
                    if ( GetMetadata(ImStr.ItemCrmID) == ob1 )
                        pgPictures.PageNumber = int.Parse(ob);
                }
            }
            
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookItem CRMImageBookItem_Load DLItems null: {0}, type: {1}", (DLItems == null), GetType()), ModuleTraceSwitch.Sw.Info);
            // insert items in the child datalist
            if ( DLItems != null)
            {
                // Ajaxify the Local datalist: it update the whole module
                ((ADNPage)Page).AddAjaxSetting(DLItems, ((ADNPage)Page).LoadedModules[ModuleID]);
                if (pgPictures != null)
                {
                    ((ADNPage)Page).AddAjaxSetting(pgPictures, ((ADNPage)Page).LoadedModules[ModuleID]);
                    if ( RadToolTipManager1 != null )
                        ((ADNPage)Page).AddAjaxSetting(pgPictures, RadToolTipManager1);
                    BindData(pgPictures.PageNumber);
                }
                else BindData(0);
            }
        }
        
		private void BindData(int wpage)
		{
    		if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookItem BindData BEG Page: {0}, RepeatColumns: {1}.", 
                    wpage,RepeatColumns),CrmImageTrace.Sw.Info);
    		if ( ( pgPictures != null ) && CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookItem BindData RecordsPerPage: {0}, pgPictures.RecordsPerPage: {1}.", 
                    RecordsPerPage,pgPictures.RecordsPerPage),CrmImageTrace.Sw.Info);
            imageItemID					    =   (pgPictures == null) ? 1:(1+pgPictures.RecordsPerPage*(wpage-1));
            rowCount                        =	0;// reset counter before binding
            SqlDataReader dr                =   null;
            try
            {
                    DLItems.RepeatDirection =   RepeatDirection;
                    DLItems.RepeatColumns   =   RepeatColumns;
                    if ( pgPictures != null )
                        dr                      =   new CRMImageDB().GetCRMImageBookFullPaged(wpage,pgPictures.RecordsPerPage,RequestEntityName, CRMEntId);
                    else dr                     =   new CRMImageDB().GetCRMImageBookFull(RequestEntityName, CRMEntId);
                    DLItems.DataSource          =   dr;
                    DLItems.DataBind();
                    if ( pgPictures != null )
                        pgPictures.RecordCount  =   rowCount;// initialized during DataBind
            }
            catch (Exception ex)
            {
                if ( CrmImageTrace.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageBook BindData ex :{0}", ex),CrmImageTrace.Sw.Info);
                throw;
            }
            finally
            {
                if (dr != null)
                    dr.Close();
            }
    		if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookItem BindData END rowCount: {0}.",rowCount),CrmImageTrace.Sw.Info);
		}
                
        /// <summary>
        /// Take the command event sent by button to build another command event and bubble it to upper datalist control
        /// sending the imageId as argument
        /// </summary>
        void  DLItems_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookItem DLItems_ItemCommand CommandEventArgs CommandName: {0}, CommandArgument: {1}",e.CommandName,e.CommandArgument),ModuleTraceSwitch.Sw.Info);
            if (e.CommandName == "DeleteImage")
            {
                ////// What to do to send to upper DataList
                string Arg          =   string.Format("{0};{1};{2}",RequestEntityName,CRMEntId,e.CommandArgument);
                CommandEventArgs ev =   new CommandEventArgs(e.CommandName,Arg);
                RaiseBubbleEvent(e.CommandSource,ev);
            }
        }
        
        RadToolTipManager _RadToolTipManager1    =   null;
        public RadToolTipManager RadToolTipManager1
        {
            get
            {
                if (_RadToolTipManager1 == null)
                    _RadToolTipManager1 = (RadToolTipManager)ChildControlHelper.FindControlRecursive("RadToolTipManager1", Page);
                return _RadToolTipManager1;
            }
            set
            {
                _RadToolTipManager1 = value;
            }
        }

        // Add a ToolTip to the loaded image
        void AddToolTipImage(CRMImageItem ImgItem)
        {
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookItem AddToolTipImage BEG ImgItem.ID: {0}, ClientID: {1}.",ImgItem.ID,ImgItem.ClientID),CrmImageTrace.Sw.Info);
            Image img                               =   (Image)ImgItem.FindControl("CrmImg");
            if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookItem AddToolTipImage img found: {0}, RadToolTipManager: {1}.",img != null, RadToolTipManager1 != null),CrmImageTrace.Sw.Info);
            if (!Object.Equals(img, null) && ( RadToolTipManager1 != null ))
            {
                string val                          =   ImgItem.imageModifiedSrc;
                if ( CrmImageTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookItem AddToolTipImage img.ClientID: {0}, url: {1}.",img.ClientID,val),CrmImageTrace.Sw.Info);
                RadToolTipManager1.TargetControls.Add(img.ClientID, val, true);
            }
            // Add confirm delete
            ImageButton BtnDelImage =   (ImageButton)ImgItem.FindControl("BtnDelImage");
            //bool hasGeneralTManager =   ((ADNPage)Page).HasToolTipManager;

            if (!Object.Equals(BtnDelImage, null) )
            {
                string msg                  =   LocalizeHelper.Localize("CONFIRM_DELETE", "Confirm Delete");
                string title                =   LocalizeHelper.Localize("DELETE", "Delete");
                ((ADNPage)Page).setClientConfirmAttributes(BtnDelImage,msg,title);
                // Tooltipyfy for text this button
                RadToolTip tt           =   new RadToolTip();
                tt.ID                   =   string.Format("tt_{0}",BtnDelImage.ID);
                tt.IsClientID           =   true;
                tt.TargetControlID      =   BtnDelImage.ClientID;
                tt.Position             =   ToolTipPosition.BottomRight;
                tt.RelativeTo           =   ToolTipRelativeDisplay.Element;
                tt.ContentScrolling     =   ToolTipScrolling.Default;
                BtnDelImage.Parent.Controls.AddAt(BtnDelImage.Parent.Controls.IndexOf(BtnDelImage),tt);
                tt.Text                 =   string.Format("Delete {0}",ImgItem.imageCaption);
                ((ADNPage)Page).AddAjaxSetting(BtnDelImage, ((ADNPage)Page).LoadedModules[ModuleID]);
                if ( RadToolTipManager1 != null )
                    ((ADNPage)Page).AddAjaxSetting(BtnDelImage, RadToolTipManager1);
            }
            // If tootip manager in Page tooltipyfy all available
            // Any edit button/image/else
            Control Ctl                 =   ImgItem.FindControl("ImgEdit");
            if (!Object.Equals(Ctl, null))
            {
                RadToolTip tt           =   new RadToolTip();
                tt.ID                   =   string.Format("tt_{0}",Ctl.ID);
                tt.TargetControlID      =   Ctl.ClientID;
                tt.IsClientID           =   true;
                tt.Position             =   ToolTipPosition.BottomRight;
                tt.RelativeTo           =   ToolTipRelativeDisplay.Element;
                tt.ContentScrolling     =   ToolTipScrolling.Default;
                Ctl.Parent.Controls.AddAt(Ctl.Parent.Controls.IndexOf(Ctl),tt);
                tt.Text                 =   string.Format("Edit {0}",ImgItem.imageCaption);
            }
            // Caption
            Ctl                         =   ImgItem.FindControl("imgCaption");
            if (!Object.Equals(Ctl, null) && (ImgItem.imageShortDescription != string.Empty) )
            {
                RadToolTip tt           =   new RadToolTip();
                tt.ID                   =   string.Format("tt_{0}",Ctl.ID);
                tt.TargetControlID      =   Ctl.ClientID;
                tt.IsClientID           =   true;
                tt.Position             =   ToolTipPosition.Center;
                tt.RelativeTo           =   ToolTipRelativeDisplay.Element;
                tt.ContentScrolling     =   ToolTipScrolling.Default;
                Ctl.Parent.Controls.AddAt(Ctl.Parent.Controls.IndexOf(Ctl),tt);
                tt.Text                 =   ImgItem.imageShortDescription;
            }
            // Category
            Ctl                         =   ImgItem.FindControl("imgCategory");
            if (!Object.Equals(Ctl, null))
            {
                RadToolTip tt           =   new RadToolTip();
                tt.ID                   =   string.Format("tt_{0}",Ctl.ID);
                tt.TargetControlID      =   Ctl.ClientID;
                tt.IsClientID           =   true;
                tt.Position             =   ToolTipPosition.Center;
                tt.RelativeTo           =   ToolTipRelativeDisplay.Element;
                tt.ContentScrolling     =   ToolTipScrolling.Default;
                Ctl.Parent.Controls.AddAt(Ctl.Parent.Controls.IndexOf(Ctl),tt);
                tt.Text                 =   ImgItem.imageCategoryText;
            }
            // ShortDescription
            Ctl                         =   ImgItem.FindControl("imgShortDescription");
            if (!Object.Equals(Ctl, null) && (ImgItem.imageShortDescription != string.Empty) )
            {
                RadToolTip tt           =   new RadToolTip();
                tt.ID                   =   string.Format("tt_{0}",Ctl.ID);
                tt.TargetControlID      =   Ctl.ClientID;
                tt.IsClientID           =   true;
                tt.Position             =   ToolTipPosition.Center;
                tt.RelativeTo           =   ToolTipRelativeDisplay.Element;
                tt.ContentScrolling     =   ToolTipScrolling.Default;
                Ctl.Parent.Controls.AddAt(Ctl.Parent.Controls.IndexOf(Ctl),tt);
                tt.Text                 =   ImgItem.imageShortDescription;
            }
            //LongDescription
            Ctl                         =   ImgItem.FindControl("imgLongDescription");
            if (!Object.Equals(Ctl, null) && (ImgItem.imageLongDescription != string.Empty) )
            {
                RadToolTip tt           =   new RadToolTip();
                tt.ID                   =   string.Format("tt_{0}",Ctl.ID);
                tt.TargetControlID      =   Ctl.ClientID;
                tt.IsClientID           =   true;
                tt.Position             =   ToolTipPosition.Center;
                tt.RelativeTo           =   ToolTipRelativeDisplay.Element;
                tt.ContentScrolling     =   ToolTipScrolling.Default;
                Ctl.Parent.Controls.AddAt(Ctl.Parent.Controls.IndexOf(Ctl),tt);
                tt.Text                 =   ImgItem.imageLongDescription;
            }
        }
        

        /// <summary>
        /// Binding for CRMImageBookImageItems: we use DB values and values sent by CRMImageBook in the local MetaData Xml container
        /// </summary>
        protected void DLItems_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            try
            {
                DbDataRecord di					=   (DbDataRecord)e.Item.DataItem;
                if ( ModuleTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmImageBookItem DLItems_ItemDataBound LoadControl: '{0}'.", layoutThumbnailModule),ModuleTraceSwitch.Sw.Info);
                
                // We get an ImageBookImageItem which is the object managing individual images
                // We keep care to transfert in its metadata the RequestEntityName which is the name of CRM entity read in DB originally
                CRMImageBookImageItem ImageItem =   (CRMImageBookImageItem)Page.LoadControl(layoutThumbnailModule);

                bool IsEditable		        =   bool.Parse(GetMetadata(ImStr.IsEditable));
                bool IsDeletable		    =   bool.Parse(GetMetadata(ImStr.IsDeletable));
                
                string AlbumPath		    =   GetMetadata(ImStr.MetaAlbumPath);
				ImageItem.BindFromDB(di,AlbumPath,
                    imageItemID++,
                    IsEditable,
                    IsDeletable,
                    RequestEntityName,
                    EntityName,
                    ModuleID,
                    e.Item.ItemIndex,
                    ( pgPictures == null ) ? 0: pgPictures.PageNumber,
                    -1,
                    "ASC");
                
                if ( pgPictures != null)
                {
                    if (rowCount == 0)
                        rowCount = (int)di["RecordCount"];
                }
                else rowCount++;

                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmImageBookItem DLItems_ItemDataBound Metadata Version: {0}.", 
                        Metadata.Version),ModuleTraceSwitch.Sw.Info);
                ImageItem.AddMetadataElement(ImStr.DBDisplayOrder,((int)di[ImStr.DBDisplayOrder]).ToString());
                ImageItem.AddMetadataElement(ImStr.ItemCrmID,GetMetadata(ImStr.ItemCrmID));
                ImageItem.AddMetadataElement(ImStr.ParentPageNum,GetMetadata(ImStr.ParentPageNum));
                ImageItem.DataBind();
                e.Item.Controls.Add(ImageItem);
                AddToolTipImage(ImageItem);
            }
            catch (Exception ex)
            {
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CRMImageBookItem DLItems_ItemDataBound ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }

		private void Page_Changed(object sender, System.EventArgs e)
		{
			if ( CrmImageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CRMImageBookItem Page_Changed PageNumber: {0}.", pgPictures.PageNumber),CrmImageTrace.Sw.Info);
			BindData(pgPictures.PageNumber);
		}
        

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }
		
        /// <summary>
        ///	Required method for Designer support - do not modify
        ///	the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            Load                        +=  new EventHandler(CRMImageBookItem_Load);
			if ( DLItems != null )
            {
				DLItems.ItemDataBound   +=  new DataListItemEventHandler(DLItems_ItemDataBound);
                DLItems.ItemCommand     +=  new DataListCommandEventHandler(DLItems_ItemCommand);
                if ( pgPictures != null )
                    pgPictures.OnMove   +=  new EventHandler(Page_Changed);
            }
		}
		#endregion
    }
}